#include "delay.h"

static uint32_t fac_us = 84;

void delay_us(uint32_t xus)
{
  uint32_t xms;		
	volatile uint32_t ticks;
	volatile uint32_t told,tnow,tcnt=0;
	volatile uint32_t reload=SysTick->LOAD;				//LOAD的值	  

  xms = xus/1000;
  xus = xus-xms;

  HAL_Delay(xms);

	ticks=xus*fac_us; 						//需要的节拍数 
	told=SysTick->VAL;        				//刚进入时的计数器值
	while(1)
	{
		tnow=SysTick->VAL;	
		if(tnow!=told)
		{	    
			if(tnow<told)
        tcnt+=told-tnow;	//这里注意一下SYSTICK是一个递减的计数器就可以了.
			else 
        tcnt+=reload-tnow+told;	    
			told=tnow;
			if(tcnt>=ticks)break;			//时间超过/等于要延迟的时间,则退出.
		}  
	}
}


void delay_ms(uint32_t xms)
{
    HAL_Delay(xms);
}

extern inline void get_ms(uint32_t *ms)
{
	*ms = HAL_GetTick();
}

extern inline uint32_t get_ms2(void)
{
	return HAL_GetTick();
}

uint32_t time_to_time(uint32_t old_tick, uint32_t new_tick)
{
	uint32_t ret = 0;
	if(old_tick > new_tick)
	{
		ret = (-1) - old_tick + new_tick;
	}
	else
	{
		ret = new_tick - old_tick;
	}
	return ret;
}

uint32_t time_to_now(uint32_t old_tick)
{
	time_to_time(old_tick, get_ms2());
}


